package de.fhhof.vinf.ssp.studienarbeit11.beans;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.regex.*;

public class Validate {

	/**
	 * This method checks if the String given in toCheck is already in the db in
	 * the column given in the String column if String is null returns false
	 * 
	 * @param String
	 *            toCheck
	 * @param String
	 *            column of db
	 * @return boolean
	 */
	public boolean isInDb(String toCheck, String column) {
		boolean isInDb = false;
		try {
			Statement stmt;
			ResultSet res;

			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/studienarbeit";
			Connection con = DriverManager.getConnection(url, "admin", "cisco");
			stmt = con.createStatement();
			try {
				res = stmt.executeQuery("Select " + column
						+ " From studienarbeit.users" + " where " + column
						+ " like '" + toCheck + "'");

				while (res.next()) {
					isInDb = true;
				}

			} catch (Exception e) {

				con.close();
				System.out.println(e);
			} finally {
				con.close();
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return isInDb;
	}

	/**
	 * This method checks if the param String is a valid e-mail. if String is
	 * null returns false
	 * 
	 * @param email
	 * @return boolean
	 */
	public boolean isValidEmail(String email) {
		// check if email meets RegEx
		try {
					Pattern p = Pattern
					.compile("^[\\w\\.\\=\\-]+@[\\w\\.\\-]+\\.[\\w]{2,4}$");
			Matcher m = p.matcher(email);
			boolean meetRegEx = m.matches();

			return meetRegEx;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * This method checks if a String only consists of letters
	 * if String is null returns false
	 * @param String input
	 * @return boolean
	 */
	public boolean isStringWithoutNumbers(String input) {
		try {
			Pattern p = Pattern.compile("[a-zA-Z]+");
			Matcher m = p.matcher(input);
			boolean meetRegEx = m.matches();

			return meetRegEx;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * This method checks if a String is without special character and at least five characters long
	 * if String is null returns false
	 * @param String input
	 * @return boolean
	 */
	public boolean isAtLeastFiveCharacters(String input) {
		try {
			Pattern p = Pattern
					.compile("[a-zA-Z_0-9][a-zA-Z_0-9][a-zA-Z_0-9][a-zA-Z_0-9][a-zA-Z_0-9]+");
			Matcher m = p.matcher(input);
			boolean meetRegEx = m.matches();

			return meetRegEx;
		} catch (Exception e) {
			return false;
		}
	}

}
